<!-- 文本框 -->
<template>
  <view class="collapse">
    <van-field
      v-show="!props.hidden"
      v-model="validateValue"
      :name="props.formItem?.id"
      :label="props.formItem?.title"
      :placeholder="props.placeholder"
      :rules="rules"
      :required="props.required"
      :readonly="props.readonly"
      :input-align="FieldInputAlign.DEFAULT"
      clearable
    >
      <template #input>
        <text />
      </template>
    </van-field>
    <van-collapse v-model="activeNames" accordion ref="collapseRef">
      <view v-if="isNotEmpty(_value)">
        <van-collapse-item
          :title="index"
          :name="index"
          v-for="(item, index) in _value"
          :key="index"
        >
          <template #title>
            <view class="collapse__title">
              <text>第 {{ index + 1 }} 项</text>
              <van-icon name="delete-o" @click="delLine(index)" />
            </view>
          </template>
          <form-render
            :ref="`formRender${index}`"
            v-model:formData="_value[index]"
            :formItems="columns"
          />
        </van-collapse-item>
      </view>
      <view class="collapse__button">
        <van-button type="primary" icon="plus" plain hairline size="mini" @click="addLine">
          添加数据
        </van-button>
      </view>
    </van-collapse>
  </view>
</template>
<script setup lang="ts">
  import { isEmpty, isNotEmpty } from '@/utils/is';
  import { ref, computed, watch } from 'vue';
  import { evalFormual } from '@/utils/evalFormual';
  import { FieldInputAlign } from '@/enums/formEnum';
  import FormRender from '@/pages/form/form-render.vue';
  import { FormDataModel } from '@/services/model/formModel';
  import { Modal, Toast } from '@/utils/uniapi/prompt';

  const emits = defineEmits(['update:value', 'labelShow']);

  const props = defineProps({
    value: {
      type: Array<FormDataModel>,
      default: () => [],
    },
    required: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    //隐藏组件的公共属性
    formula: {
      type: Object,
      default: () => {
        return {
          showFormula: '', //回显用，因为包含表单字段的时候会出现表单名称
          calcFormula: '', //解析用，表单名称对应为formData.fieldxxxx
        };
      },
    },
    formItem: {
      type: Object,
      default: () => {},
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    rule: {
      type: Object,
      default: () => null,
    },
    placeholder: {
      type: String,
      default: '请输入内容',
    },
    enableScan: {
      type: Boolean,
      default: false,
    },
    hidden: {
      type: Boolean,
      default: false,
    },
    maxSize: {
      type: Number,
      default: 0,
    },
  });

  /** 计算属性：_value */
  const _value = computed({
    get() {
      return props.value;
    },
    set(val) {
      emits('update:value', val);
    },
  });

  /** 用于必填校验 */
  const validateValue = computed(() => {
    return isNotEmpty(props.value) ? '1' : '';
  });

  /** 校验规则 */
  const rules = computed(() => {
    console.log('rules--->', props.rule);
    if (isEmpty(props.rule)) {
      return [];
    } else {
      return props.rule;
    }
  });

  const columns = computed(() => {
    return props.formItem.props.columns;
  });

  const doFormula = () => {
    let hidden = evalFormual(props.formula.calcFormula, props.formData);
    //如果隐藏，同时也隐藏label,通知父组件去隐藏，因为label不在当前界面
    //调用父组件FormDesignRender 的方法：
    emits('labelShow', props.formItem, hidden);
  };

  watch(
    () => props.formData,
    () => {
      doFormula();
    },
    { immediate: true, deep: true },
  );

  const collapseRef = ref();
  /** 当前展开的面板 */
  const activeNames = ref<number>(0);

  /** 添加数据 */
  const addLine = () => {
    if (props.maxSize > 0 && _value.value.length >= props.maxSize) {
      Toast(`最多加${props.maxSize}行`);
    } else {
      let row: any = {};
      columns.value.forEach((col: any) => (row[col.id] = undefined));
      _value.value.push(row);
      activeNames.value = _value.value.length - 1;
    }
  };

  /** 删除数据 */
  const delLine = (index: number) => {
    Modal({
      title: '提示',
      content: '您确定要删除该行数据吗？',
    }).then((res: any) => {
      if (res.confirm) {
        _value.value.splice(index, 1);
      }
      if (res.cancel) {
        console.log('close');
      }
    });
  };
</script>
<style scoped lang="scss">
  .collapse {
    &__title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 30rpx;
    }
    &__button {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 20rpx 30rpx;
      background-color: #fff;
    }
  }
</style>
